package utils

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

// FindProcessByInode 通过inode查找对应的进程
func FindProcessByInode(inode string) (int32, string, string, string) {
	if inode == "0" {
		return 0, "", "", ""
	}

	procDir := "/proc"
	dirs, err := os.ReadDir(procDir)
	if err != nil {
		return 0, "", "", ""
	}

	for _, dir := range dirs {
		if !dir.IsDir() {
			continue
		}

		pidStr := dir.Name()
		pid, err := strconv.ParseInt(pidStr, 10, 32)
		if err != nil {
			continue
		}

		// 检查进程的文件描述符
		fdDir := filepath.Join(procDir, pidStr, "fd")
		fds, err := os.ReadDir(fdDir)
		if err != nil {
			// 权限不足或进程已结束
			continue
		}

		for _, fd := range fds {
			fdPath := filepath.Join(fdDir, fd.Name())
			link, err := os.Readlink(fdPath)
			if err != nil {
				continue
			}

			// 检查是否匹配socket inode
			if strings.Contains(link, "socket:["+inode+"]") {
				// 获取进程信息
				processName, executable, username := GetProcessInfo(int32(pid))
				return int32(pid), processName, executable, username
			}
		}
	}

	return 0, "", "", ""
}

// GetProcessInfo 获取进程信息
func GetProcessInfo(pid int32) (string, string, string) {
	procPath := fmt.Sprintf("/proc/%d", pid)

	// 获取进程名
	commFile := filepath.Join(procPath, "comm")
	commData, err := os.ReadFile(commFile)
	processName := "unknown"
	if err == nil {
		processName = strings.TrimSpace(string(commData))
	}

	// 获取可执行文件路径
	exeFile := filepath.Join(procPath, "exe")
	executable, err := os.Readlink(exeFile)
	if err != nil {
		executable = "unknown"
	}

	// 获取用户名（简化实现，实际可能需要通过UID查找）
	username := "unknown"
	statusFile := filepath.Join(procPath, "status")
	if statusData, err := os.ReadFile(statusFile); err == nil {
		lines := strings.Split(string(statusData), "\n")
		for _, line := range lines {
			if strings.HasPrefix(line, "Uid:") {
				fields := strings.Fields(line)
				if len(fields) > 1 {
					uid := fields[1]
					// 这里简化处理，实际应该通过UID查找用户名
					username = "uid:" + uid
				}
				break
			}
		}
	}

	return processName, executable, username
}
